package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReService;
import com.itheima.health.service.ReportService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("report")
public class ReController {
    @DubboReference
    private ReService reService;

    @GetMapping("getMemberByMonth")
    public Result getMemberByMonth(String startMonth,String endMonth) {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        try {
            //起始月份
            Date startMon = sdf.parse(startMonth);
            //结束月份
            Date endMon = sdf.parse(endMonth);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endMon);
            //获取结束年月
            int year1 = calendar.get(Calendar.YEAR);
            int month1 = calendar.get(Calendar.MONTH);
            //获取开始年月
            calendar.setTime(startMon);
            int year2 = calendar.get(Calendar.YEAR);
            int month2 = calendar.get(Calendar.MONTH);
            //两个日期相差的月数
            int monthCount;
            if (year1 == year2) {
                monthCount = month1 - month2;
            } else {
                monthCount = 12 * (year1 - year2) + month1 - month2;
            }
            calendar.add(Calendar.MONTH, -1);
            //获取起始月份到结束月份
            List<String> months = new ArrayList<>();
            for (int i = 0; i <= monthCount; i++) {
                calendar.add(Calendar.MONTH, 1);//add方法用于计算
                months.add(sdf.format(calendar.getTime()));
            }
            //根据月份查询对应的会员数量
            List<Integer> memberCount = reService.findMemberCountByMonths(months);

            Map<String, Object> data = new HashMap<>();
            data.put("months", months);
            data.put("memberCount", memberCount);
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}





